﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Net;
using System.Windows.Data;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.Shell;
using MyDeeWeibo.Classes;

namespace MyDeeWeibo
{
    public partial class MyReplyView : PhoneApplicationPage
    {
        public static DeeSendBase SdkCommentReply = null;
        private const string SHARE_WEIBO_TEXT = "回复";

        private DeeCmdBase cmdBase;
        private DeeNetEngine netEngine;

        #region Definie Dependency Property
        /// <summary>
        /// Define all this page's public proterties for data binding.
        /// </summary>

        #region IsProgressIndicatorVisibleProperty
        public static readonly DependencyProperty IsProgressIndicatorVisibleProperty =
            DependencyProperty.Register("IsProgressIndicatorVisible",
            typeof(bool),
            typeof(MyReplyView),
            new PropertyMetadata(false));

        public bool IsProgressIndicatorVisible
        {
            get { return (bool)GetValue(IsProgressIndicatorVisibleProperty); }
            set { SetValue(IsProgressIndicatorVisibleProperty, value); }
        }
        #endregion

        #region WordCountProperty
        public static readonly DependencyProperty WordCountProperty =
            DependencyProperty.Register("WordCount", typeof(string), typeof(MyReplyView), new PropertyMetadata((string)"140"));

        public string WordCount
        {
            get { return (string)GetValue(WordCountProperty); }
            set { SetValue(WordCountProperty, value); }
        }
        #endregion

        #endregion

        public MyReplyView()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            SystemTray.ProgressIndicator = new ProgressIndicator();
            SystemTray.ProgressIndicator.Text = "网络通讯中";

            Binding bindingData;
            bindingData = new Binding("IsProgressIndicatorVisible");
            bindingData.Source = this;
            bindingData.Mode = BindingMode.TwoWay;
            BindingOperations.SetBinding(SystemTray.ProgressIndicator, ProgressIndicator.IsVisibleProperty, bindingData);
            BindingOperations.SetBinding(SystemTray.ProgressIndicator, ProgressIndicator.IsIndeterminateProperty, bindingData);


            if (SdkCommentReply.GetType() == typeof(SdkComReply))
            {
                TitleBlock.Text = string.IsNullOrEmpty(SdkCommentReply.TitleText) ? SHARE_WEIBO_TEXT : SdkCommentReply.TitleText;

                if (!string.IsNullOrEmpty(SdkCommentReply.Message))
                {
                    this.StatusMessageBox.Text = SdkCommentReply.Message;
                    this.StatusMessageBox.SelectionStart = this.StatusMessageBox.Text.Length;
                }
            }
            else
            {
                if (SdkCommentReply.Completed != null)
                {
                    SendCompletedEventArgs err = new SendCompletedEventArgs()
                    {
                        IsSendSuccess = false,
                        ErrorCode = DeeErrCode.XPARAM_ERR,
                        Response = "Unexpect Error.",
                    };
                    SdkCommentReply.Completed.Invoke(SdkCommentReply, err);
                }
            }
        }

        private void StatusMessageBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            WordCount = (140 - StatusMessageBox.Text.Length).ToString();
        }

        private void SendTextStatus()
        {
            IsProgressIndicatorVisible = true;
            this.StatusMessageBox.IsReadOnly = true;

            netEngine = new DeeNetEngine();
            cmdBase = new cmdCommentCreate
            {
                comment = StatusMessageBox.Text,
                acessToken = SdkCommentReply.AccessToken,
                //acessTokenSecret = sdkSendBase.AccessTokenSecret
                id = SdkCommentReply.id,
                cid = SdkCommentReply.cid,
            };

            netEngine.RequestCmd(DeeRequestType.COMMENT_REPLY, cmdBase, requestCompleted);
        }

        void requestCompleted(DeeRequestType requestType, DeeResponse response)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                IsProgressIndicatorVisible = false;
                this.StatusMessageBox.IsReadOnly = false;

                if (SdkCommentReply.Completed != null)
                {
                    SendCompletedEventArgs e = new SendCompletedEventArgs()
                    {
                        IsSendSuccess = (response.errCode == DeeErrCode.SUCCESS),
                        ErrorCode = response.errCode,
                        Response = response.content
                    };
                    SdkCommentReply.Completed.Invoke(SdkCommentReply, e);
                }

                if (NavigationService.CanGoBack)
                    NavigationService.GoBack();
            });
        }

        #region Func Part Fake AppBar


        private void ApplicationBarIconButton_SendClick(object sender, System.EventArgs e)
        {
            int remainLenth = Convert.ToInt32(WordCount);
            if (remainLenth < 0)
                MessageBox.Show("微博信息量超出字符长度限制。", "错误", MessageBoxButton.OK);
            else if (remainLenth >= 140)
                MessageBox.Show("请保证您的微博包含有效信息。", "错误", MessageBoxButton.OK);
            else
            {
                SendTextStatus();
            }
        }

        #endregion
    }
}